package com.example.yuanboot.filter;

import cn.hutool.core.util.StrUtil;
import com.example.yuanboot.service.common.IRedisService;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码
 *
 * @author qingyan 2021-08-26
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    private final IRedisService redisService;
    private final AuthenticationFailureHandler authenticationFailureHandler;

    public VerifyCodeFilter(IRedisService redisService, AuthenticationFailureHandler authenticationFailureHandler) {
        this.redisService = redisService;
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String defaultFilterProcessUrl = "/login";
        try {
            if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
                // 验证码验证
                String requestCaptcha = request.getParameter("code");
                if (StrUtil.isEmpty(requestCaptcha)) throw new AuthenticationServiceException("验证码不能为空!");
                String uuid = request.getParameter("uuid");
                String code = (String)redisService.get(uuid);
                if (!StrUtil.equalsIgnoreCase(code, requestCaptcha)) {
                    throw new AuthenticationServiceException("验证码错误!");
                }
            }
        } catch (AuthenticationException e) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, e);
//            return;
        }

        chain.doFilter(request, response);
    }

}
